package com.wordpress.fatecode.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.wordpress.fatecode.entity.User;
import com.wordpress.fatecode.jdbc.Conexao;

public class UserDAO {
	private Connection connection;
	private ResultSet resultSet;
	private PreparedStatement stmt;
	
	
	public void salvar(User e) {
		connection =  new Conexao().getConnection();
		try {
			stmt = connection.prepareStatement("INSERT INTO USUARIO(?, ?");
			stmt.setString(1, e.getLogin());
			stmt.setString(2, e.getSenha());
			
			stmt.execute();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
	}

	public void alterar(User e) {
		connection =  new Conexao().getConnection();
		try {
			stmt = connection.prepareStatement("UPDATE USUARIO SET nome = ?, senha = ?");
			stmt.setString(1, e.getLogin());
			stmt.setString(2, e.getSenha());
			
			stmt.execute();
			
			close();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
	}

	
	public void excluirUsuario(String nome) {
		connection =  new Conexao().getConnection();
		try {
			stmt = connection.prepareStatement("DELETE FROM USUARIO WHERE nome = ?");
			stmt.setString(1, nome);
			
			stmt.execute();
			
			close();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	}


	public User buscar(String nome) {
		connection =  new Conexao().getConnection();
		try {
			stmt = connection.prepareStatement("DELETE FROM USUARIO WHERE nome = ?");
			resultSet = stmt.executeQuery();
			
			if (resultSet.next()) {
				String login = resultSet.getString("nome");
				String senha = resultSet.getString("senha");
				
				close();
				User user = new User(login, senha);
				
				return user;
			}
			
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		return null;
	}
	public void close() {
		try {
			if (resultSet != null)
				resultSet.close();

			if (stmt != null)
				stmt.close();

			if (connection != null)
				connection.close();

		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

}
